package com.robooot.business_counter.service;


import com.robooot.business_counter.exception.BizException;
import com.robooot.business_counter.model.RemoteUrl;
import com.robooot.business_counter.util.JsonUtil;
import com.robooot.common.core.util.DateFormatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.RestTemplate;


import java.text.MessageFormat;
import java.util.Date;
import java.util.Map;

@Service
public class RemoteService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RemoteUrl remoteUrl;


    //TODO
    public Map callWithSign(String url, Map params) {
        String nonce = DateFormatUtil.formatDate(new Date(), "yyyyMMddHHmmss");
        String unsigned = MessageFormat.format("serverId={0}&apiKey={1}&nonce={2}", remoteUrl.getServerId(), remoteUrl.getApiKey(), nonce);
        params.put("serverId", remoteUrl.getServerId());
        params.put("nonce", nonce);
        params.put("signature", DigestUtils.md5DigestAsHex(unsigned.getBytes()));
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, params, String.class);
        Map result = JsonUtil.jsonStr2Bean(responseEntity.getBody(), Map.class);
        if ((int) result.get("result") != 0) {
            throw new BizException((String) result.get("message"));
        }
        return (Map) result.get("data");
    }
}
